package com.tjyx.common.util;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.RequestContext;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.servlet.ServletRequestContext;

@SuppressWarnings({ "serial", "deprecation","unchecked" })
public class UploadFilePic {
	
	private static String dir_name = "";
	private static  int type=0;
	private static String fileExt = "jpg,jpeg,bmp,gif,png";
	private static Long maxSize = 0l;

	public static  void setDir_name(String dir_name) {
		UploadFilePic.dir_name = dir_name;
	}

	public static String getDir_name() {
		return UploadFilePic.dir_name;
	}
	
	public static HashMap begin_upload(HttpServletRequest request,
			HttpServletResponse response,int type) {
		if(type==1){//如果是新闻图片上传
			dir_name="newsImg";
		}else if(type==2){//如果是产品图片上传
			dir_name="productImg";
		}
		UploadFilePic.type=type;
		HashMap param_hm = new HashMap();
		try {
			request.setCharacterEncoding("utf-8");
			RequestContext requestContext = new ServletRequestContext(request);
			if (FileUpload.isMultipartContent(requestContext)) {
				DiskFileItemFactory factory = new DiskFileItemFactory();
				File temp_file = new File(request.getRealPath("") + "//"
						+ getDir_name() + "//");
				if (!temp_file.exists()) {
					temp_file.mkdirs();
				}
				factory.setRepository(temp_file);
				ServletFileUpload upload = new ServletFileUpload(factory);
				upload.setHeaderEncoding("utf-8");
				upload.setSizeMax(-1);
				List items = new ArrayList();
				items = upload.parseRequest(request);
				Iterator it = items.iterator();
				while (it.hasNext()) {
					FileItem fileItem = (FileItem) it.next();
					if (fileItem.isFormField()) {
						param_hm.put(fileItem.getFieldName(), new String(
								fileItem.getString().getBytes("iso8859-1"),
								"utf-8"));
					} else {
						if (fileItem.getName() != null&&!fileItem.getName().equals("")) {
							String filename = UUID.randomUUID().toString();
							String extensionName = fileItem.getName().substring(
											fileItem.getName().lastIndexOf(".") + 1);
							File newFile = new File(request.getRealPath("")
									+ "//" + getDir_name() + "//" + filename
									+ "." + extensionName);
							if(type==1||type==2){
								if(!judgeFile(type,request,extensionName,fileItem)){
									return null;
								};
							}
							fileItem.write(newFile);
							param_hm.put("filename",filename+"."+extensionName);
						} else {
							if(type==2){
								request.setAttribute("uploadMessage", "图片不能为空");
							}
						}
					}
				}
			}
		} catch (UnsupportedEncodingException e2) {
			e2.printStackTrace();
		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return param_hm;
	}
	
	private static Boolean judgeFile(int type,HttpServletRequest request,String extensionName,FileItem fileItem) throws IOException {
		/*检查文件类型*/
		if (("," + fileExt.toLowerCase() + ",").indexOf("," + extensionName.toLowerCase() + ",") < 0){
			request.setAttribute("uploadMessage", "不允许上传此类型的文件");
			return false;
		}
		if(type==2){//如果是添加产品的话，图片不能为空
			/*文件是否为空*/
			if (fileItem.getSize() == 0){
				request.setAttribute("uploadMessage", "图片不能为空");
				return false; 
			}	
		}
		/*检查文件大小*/
		if (maxSize > 0 && fileItem.getSize() > maxSize){
			request.setAttribute("uploadMessage", "上传图片的大小超出限制");
			return false;
		}
		return true;
	}

}
